package org.jeecg.modules.prodorder.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.prodorder.entity.ProductionOrderInfo;
import org.jeecg.modules.prodorder.mapper.ProductionOrderInfoMapper;
import org.jeecg.modules.prodorder.service.IProductionOrderInfoService;
import org.jeecg.modules.prodorder.vo.OpenBomVO;
import org.jeecg.modules.prodorder.vo.OpenProdOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 生产工单
 * @Date:   2021-09-09
 * @Version: V1.0
 */
@Service
public class ProductionOrderInfoServiceImpl extends ServiceImpl<ProductionOrderInfoMapper, ProductionOrderInfo> implements IProductionOrderInfoService {

	@Autowired
	ProductionOrderInfoMapper productionOrderInfoMapper;
	
	@Override
	public void addProductionOrderInfo(ProductionOrderInfo productionOrderInfo) {
	   //新增时设置hasChild为0
	    productionOrderInfo.setHasChild(IProductionOrderInfoService.NOCHILD);
		if(oConvertUtils.isEmpty(productionOrderInfo.getPid())){
			productionOrderInfo.setPid(IProductionOrderInfoService.ROOT_PID_VALUE);
		}else{
			//如果当前节点父ID不为空 则设置父节点的hasChildren 为1
			ProductionOrderInfo parent = baseMapper.selectById(productionOrderInfo.getPid());
			if(parent!=null && !"1".equals(parent.getHasChild())){
				parent.setHasChild("1");
				baseMapper.updateById(parent);
			}
		}
		baseMapper.insert(productionOrderInfo);
	}
	
	@Override
	public void updateProductionOrderInfo(ProductionOrderInfo productionOrderInfo) {
		ProductionOrderInfo entity = this.getById(productionOrderInfo.getId());
		if(entity==null) {
			throw new JeecgBootException("未找到对应实体");
		}
		String old_pid = entity.getPid();
		String new_pid = productionOrderInfo.getPid();
		if(!old_pid.equals(new_pid)) {
			updateOldParentNode(old_pid);
			if(oConvertUtils.isEmpty(new_pid)){
				productionOrderInfo.setPid(IProductionOrderInfoService.ROOT_PID_VALUE);
			}
			if(!IProductionOrderInfoService.ROOT_PID_VALUE.equals(productionOrderInfo.getPid())) {
				baseMapper.updateTreeNodeStatus(productionOrderInfo.getPid(), IProductionOrderInfoService.HASCHILD);
			}
		}
		baseMapper.updateById(productionOrderInfo);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteProductionOrderInfo(String id) throws JeecgBootException {
		//查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    ProductionOrderInfo productionOrderInfo = this.getById(idVal);
                    String pidVal = productionOrderInfo.getPid();
                    //查询此节点上一级是否还有其他子节点
                    List<ProductionOrderInfo> dataList = baseMapper.selectList(new QueryWrapper<ProductionOrderInfo>().eq("pid", pidVal).notIn("id",Arrays.asList(idArr)));
                    if((dataList == null || dataList.size()==0) && !Arrays.asList(idArr).contains(pidVal)
                            && !sb.toString().contains(pidVal)){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            ProductionOrderInfo productionOrderInfo = this.getById(id);
            if(productionOrderInfo==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(productionOrderInfo.getPid());
            baseMapper.deleteById(id);
        }
	}
	
	@Override
    public List<ProductionOrderInfo> queryTreeListNoPage(QueryWrapper<ProductionOrderInfo> queryWrapper) {
        List<ProductionOrderInfo> dataList = baseMapper.selectList(queryWrapper);
        List<ProductionOrderInfo> mapList = new ArrayList<>();
        for(ProductionOrderInfo data : dataList){
            String pidVal = data.getPid();
            //递归查询子节点的根节点
            if(pidVal != null && !"0".equals(pidVal)){
                ProductionOrderInfo rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }
	
	/**
	 * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
	 * @param pid
	 */
	private void updateOldParentNode(String pid) {
		if(!IProductionOrderInfoService.ROOT_PID_VALUE.equals(pid)) {
			Integer count = baseMapper.selectCount(new QueryWrapper<ProductionOrderInfo>().eq("pid", pid));
			if(count==null || count<=1) {
				baseMapper.updateTreeNodeStatus(pid, IProductionOrderInfoService.NOCHILD);
			}
		}
	}

	/**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private ProductionOrderInfo getTreeRoot(String pidVal){
        ProductionOrderInfo data =  baseMapper.selectById(pidVal);
        if(data != null && !"0".equals(data.getPid())){
            return this.getTreeRoot(data.getPid());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<ProductionOrderInfo> dataList = baseMapper.selectList(new QueryWrapper<ProductionOrderInfo>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(ProductionOrderInfo tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }
    
    /**
     * 通过订单id查询物料分析列表
     */
	@Override
	public List<OpenBomVO> queryBomListByOrderId(String orderId,String styleId) {
		List<OpenBomVO> goldList = productionOrderInfoMapper.queryGoldBomListByOrderId(orderId,styleId);
		List<OpenBomVO> stoneList = productionOrderInfoMapper.queryStoneBomListByOrderId(orderId,styleId);
		List<OpenBomVO> accessoryList = productionOrderInfoMapper.queryAccessoryBomListByOrderId(orderId,styleId);
		List<OpenBomVO> allList = new ArrayList<>();
		allList.addAll(goldList);
		allList.addAll(stoneList);
		allList.addAll(accessoryList);
		return allList;
	}

    /**
     * 通过订单id查询拟生成的开单单列表
     */
	@Override
	public List<OpenProdOrderVO> queryOpenListByOrderId(String orderId,String styleId) {
		List<OpenProdOrderVO> list = productionOrderInfoMapper.queryOpenListByOrderId(orderId,styleId);
		int i = 0;
		for(OpenProdOrderVO vo : list) {
			i++;
			vo.setSn(getSn(i));
		}
		return list;
	}
	


	/**
	 * 合并工单
	 */
	@Override
	@Transactional
	public Integer mergeByIds(List<String> ids) {
		int i = 0;//合并记录数。
		if(!ids.isEmpty()) {
			String prodOrderCode = String.valueOf(FillRuleUtil.executeRule("prod_num_code",null));//工单号
			String orderInfoId = "";
			String styleCusInfoId = "";
			String pid = "";
			Integer count = 0;
			if(!ids.isEmpty()) {
				int size = ids.size();
				for(String id : ids) {
					ProductionOrderInfo productionOrderInfo = this.getById(id);
					if(productionOrderInfo.getCount() == 0) {//如果该工单的存货数量为0，则跳过，不合并该工单。
						if(size == 2) {//如果只有两条工单并且有一条工单的存货数量是0，则合并操作无意义，无需执行。
							break;
						} else {
							continue;
						}
					}
					i++;
					count += productionOrderInfo.getCount();//合并数量
					orderInfoId = productionOrderInfo.getOrderInfoId();
					styleCusInfoId = productionOrderInfo.getStyleCusInfoId();
					pid = productionOrderInfo.getPid();
					UpdateWrapper<ProductionOrderInfo> updateWrapper = new UpdateWrapper<>();
					updateWrapper.in("id", id);
					updateWrapper.set("is_merged", "1");
					updateWrapper.set("merge_prod_order_code",prodOrderCode);
					productionOrderInfoMapper.update(productionOrderInfo, updateWrapper);
				}
				if(!"".equals(orderInfoId)) {
					ProductionOrderInfo mergeProductionOrderInfo = new ProductionOrderInfo();
					String max = productionOrderInfoMapper.getMaxSnByOrderInfoId(orderInfoId);
					Integer currSn = Integer.parseInt(max) + 1;
					String strCurrSn = getSn(currSn);
					mergeProductionOrderInfo.setCount(count);
					mergeProductionOrderInfo.setProdOrderCode(prodOrderCode);//工单号
					mergeProductionOrderInfo.setOrderInfoId(orderInfoId);//订单ID
					mergeProductionOrderInfo.setStyleCusInfoId(styleCusInfoId);//款式ID
					mergeProductionOrderInfo.setSn(strCurrSn);
					mergeProductionOrderInfo.setProdOrderType(5);//工单类型：1开单单 2拆单单 3回收单 4补单单 5合并单
					mergeProductionOrderInfo.setPid(pid);//根节点
					this.save(mergeProductionOrderInfo);
				}
			}
		}
		return i;
	}
	

	/**
	 * 通过订单id获取下一拆分页的字符串
	 */
	@Override
	public String getNextStartSn(String orderInfoId) {
		String currMaxSnString = productionOrderInfoMapper.getMaxSnByOrderInfoId(orderInfoId);
		Integer nextSnInteger = Integer.parseInt(currMaxSnString) + 1;
		System.out.println("nextSnInteger=============="+nextSnInteger);
		return this.getSn(nextSnInteger);
	}

	
	/**
	 * 获取拆分页（字符数字形式，不足两位的前面补0）
	 * @param sn
	 * @return
	 */
	private String getSn(Integer sn) {
		if(sn < 10) {
			return "0"+String.valueOf(sn);
		} else {
			return String.valueOf(sn);
		}
	}
}
